package com.itheima.leyou.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.leyou.common.exception.LyException;
import com.itheima.leyou.common.utils.RegexUtils;
import com.itheima.leyou.dto.Payload;
import com.itheima.leyou.dto.UserDTO;
import com.itheima.leyou.dto.UserDetail;
import com.itheima.leyou.entity.User;
import com.itheima.leyou.mapper.UserMapper;
import com.itheima.leyou.service.UserService;
import com.itheima.leyou.utils.JwtUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.itheima.leyou.common.constants.MQConstants.ExchangeConstants.SMS_EXCHANGE_NAME;
import static com.itheima.leyou.common.constants.MQConstants.RoutingKeyConstants.VERIFY_CODE_KEY;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>implements UserService {

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Autowired
    private JwtUtils jwtUtils;


    private final String KEY_PREFIX="user.leyou.id:";
    private StringRedisTemplate stringRedisTemplate;
    private AmqpTemplate amqpTemplate;

    public UserServiceImpl(StringRedisTemplate stringRedisTemplate,AmqpTemplate amqpTemplate ){
        this.stringRedisTemplate= stringRedisTemplate;
        this.amqpTemplate=amqpTemplate;
    }



    @Override
    public UserDTO loginUser(String username, String password) {
        User user = this.query().eq(null != username, "username", username).one();
        if(user==null){
            throw new LyException(400,"用户名不存在");
        }
        boolean flag = passwordEncoder.matches(password, user.getPassword());
        if(!flag){
            throw new LyException(400,"密码错误");
        }
        return new UserDTO(user);

    }

    @Override
    @Transactional
    public void registry(User user, String code) {
        if(user==null){
            throw new LyException(400,"请求参数不能为空");
        }
        String codeVar = stringRedisTemplate.opsForValue().get(KEY_PREFIX + user.getPhone());
        if(StringUtils.isEmpty(code)||(!code.equalsIgnoreCase(codeVar))){
            throw new LyException(400,"验证码不存在或者验证码错误");
        }

        //对密码进行加盐加密
        String encode = passwordEncoder.encode(user.getPassword());
        //明文和加密进行匹配
        //passwordEncoder.matches("123456",encode);
        //存到数据库中
        user.setPassword(encode);
        save(user);
    }

    /**
     * 发送短息，并发送消息到,mq监听机制
     * @param phone
     */
    @Override
    public void sendMgs(String phone) {
        //1.验证手机号码
        if(!RegexUtils.isPhone(phone)){
            throw  new LyException(400,"手机号格式不正确");
        }

        //生成验证码
        String code = RandomStringUtils.randomNumeric(6);
        //保存验证码到redis中
        stringRedisTemplate.opsForValue().set(KEY_PREFIX+phone,code,5, TimeUnit.MINUTES);

        //发送消息到ly-sms
        Map<String,String> map = new HashMap<>();
        map.put("phone",phone);
        map.put("code",code);
        //发送消息到mq
        amqpTemplate.convertAndSend(SMS_EXCHANGE_NAME, VERIFY_CODE_KEY, map);
    }

    @Override
    public Boolean isExists(String data, Integer type) {
//        if(type!=1&&type!=2){
//            throw new LyException(400,"请求 参数不存在");
//        }

//        return this.query().eq(type == 1, "username", data)
//                .eq(type == 2, "phone", data)
//                .count()==1;


        String num = null;
        switch (type){
            case 1:
                num="username";
                if(StringUtils.isEmpty(data)){
                    throw new LyException(400,"请求参数不存在");
                }
                break;
            case 2:
                num="phone";
                if(!RegexUtils.isPhone(data)){
                    throw new LyException(400,"请求参数不存在");
                }
                break;
            default:
                throw new LyException(400,"查询参数有误");
        }
        //判断用户名和手机号是否存在
        return this.query().eq(num, data).count()==1;

    }

    /**
     * 登录过程中进行token的校验
     * @param token
     * @return
     */
    @Override
    public UserDetail checkLogin(String token) {
        // 解析token
        Payload payload = jwtUtils.parseJwt(token);
        UserDetail userDetail = payload.getUserDetail();
        return userDetail;

    }
}
